/* NOTICE
 
    Jim - the Java Image Manager, copyright (c) 2005 - 2007 Grant Gardner 
 
    Jim is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    Jim is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
  
    In addition, as a special exception, you are permitted to link this code
    with the 3rd party libraries required to compile this file and to
    distribute a linked combination including them. You must obey the
    GNU General Public License in all respects for all of the code except for
    those 3rd party libraries that are licenced under terms incompatible with the
    GNU General Public License.  
 
 
 NOTICE */

package au.com.lastweekend.jim.model;

import java.awt.Image;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;

import javax.naming.Context;

import org.apache.log4j.Logger;

import au.com.lastweekend.jim.imagebase.DefaultExternalImporter;
import au.com.lastweekend.jim.imagebase.ImageBase;
import au.com.lastweekend.jim.imagebase.ImageBaseDirectory;
import au.com.lastweekend.jim.imagebase.ImageManager;
import au.com.lastweekend.jim.imagebase.LDAPImageBase;
import au.com.lastweekend.jim.imagebase.LDIFImageBase;
import au.com.lastweekend.jim.imagebase.NullImageBase;
import au.com.lastweekend.jim.imagebase.TagHandler;
import au.com.lastweekend.jim.imagebase.TagHandlerFactory;
import au.com.lastweekend.jim.swing.LIFOListModel;
import au.com.lastweekend.jim.swing.LRUImageCache;
import au.com.lastweekend.jim.util.SingletonWorker;
import au.com.lastweekend.jim.view.JimFrame.JimFrameModel;
import au.com.lastweekend.jim.view.JimFullScreen.JimFullScreenModel;
import au.com.lastweekend.jim.view.JimViewPort.JimViewPortModel;

public class JimModel implements JimFrameModel, JimViewPortModel, JimFullScreenModel, TagHandlerFactory {

    private static final Logger LOG = Logger.getLogger(JimModel.class);

    private static final int MIN_SLIDE_SIZE = 80;
    private static final int MAX_SLIDE_SIZE = 300;
    public static final int SLIDE_SIZE_INCREMENT = 10;
    private JimConfiguration configuration = new JimConfiguration();
    private ImageManager imageManager;
    private ImageBase imageBase;
    private SingletonWorker worker;

    private Map<File, Image> imageCache;

    private KeywordTreeModel keywordModel;

    private MetadataTableModel metadataModel;

    public JimViewPortModel getJimViewPortModel() {

        return this;
    }

    public LIFOListModel<File> getFolderListModel() {

        return configuration.getRecentMoveFolders();
    }

    public JimConfiguration getConfiguration() {

        return configuration;
    }

    public ImageManager getImageManager() {

        if (imageManager == null) {
            imageManager = new ImageManager(getImageBase(), new DefaultExternalImporter());

        }

        return imageManager;
    }

    public ImageBase getImageBase() {

        if (imageBase == null) {
            ImageBase newImageBase;

            JimConfiguration config = configuration;
            switch (config.getImageBaseType()) {
                case LDAP :

                    Map<String, String> env = new HashMap<String, String>();
                    env.put(Context.SECURITY_AUTHENTICATION, "simple");
                    env.put(Context.SECURITY_PRINCIPAL, config.getLdapBindDN());
                    env.put(Context.SECURITY_CREDENTIALS, config.getLdapBindPwd());

                    try {
                        String ldapBindURL = config.getLdapBindURL();
                        newImageBase = new LDAPImageBase(env, ldapBindURL, this);
                        LOG.info("Connected to " + ldapBindURL);
                    } catch (Exception e) {
                        LOG.warn("Can't connect to LDAP", e);
                        newImageBase = null;
                    }
                    break;

                case LDIF :
                    File ldifFile = new File(config.getLdifFile());
                    try {
                        newImageBase = new LDIFImageBase(ldifFile, this);
                        LOG.info("Read LDIF file " + ldifFile);
                    } catch (IOException e1) {
                        LOG.warn("Unable to use LDIF " + ldifFile, e1);
                        newImageBase = null;
                    }
                    break;

                default :
                    LOG.warn("imageBase not specified, no database functions will be available");
                    newImageBase = null;
            }

            if (newImageBase == null) {
                newImageBase = new NullImageBase();
            }

            this.imageBase = newImageBase;
        }

        return this.imageBase;

    }

    public SingletonWorker getWorker() {

        if (worker == null) {
            worker = new SingletonWorker();
            worker.start();
        }

        return worker;
    }

    public TagHandler makeTagHandler(final ImageBase imageBase, final ImageBaseDirectory imageBaseDirectory) {

        return new TagHandler() {

            public void setTag(final int tagType, final int formatCode, final Object value) {

                Runnable runnable = new Runnable() {

                    public void run() {

                        imageBase.replaceTag(imageBaseDirectory, tagType, formatCode, value);

                    }
                };
                getWorker().addWork(runnable);

            }
        };
    }

    /**
     * @param models
     */
    public void saveOpenSheets(Collection<ContactSheetListModel> models) {

        StringBuffer buffer = new StringBuffer();
        String sep = "";

        for (ContactSheetBaseModel listModel : models) {
            buffer.append(sep);
            if (listModel instanceof ImageDirectoryModel) {
                ImageDirectoryModel model = (ImageDirectoryModel) listModel;
                buffer.append(model.getDirectory().getPath());
            }
            sep = "^";

        }

        getConfiguration().setProperty(JimConfiguration.OPEN_SHEETS, buffer.toString());

    }

    public Collection<ContactSheetListModel> restoreOpenSheets() {

        String sheetsProperty = getConfiguration().getProperty(JimConfiguration.OPEN_SHEETS);
        Pattern splitPattern = Pattern.compile("^", Pattern.LITERAL);
        String[] splitProperty = splitPattern.split(sheetsProperty);
        Collection<ContactSheetListModel> results = new ArrayList<ContactSheetListModel>();
        for (String directory : splitProperty) {
            if (directory != null && !(directory.length() == 0)) {
                results.add(getContactSheetModel(new File(directory)));
                LOG.info("Restoring open sheet for " + directory);
            }
        }

        return results;
    }

    public ContactSheetListModel getContactSheetModel(File chosenDir) {

        ImageDirectoryModel imageDirectoryModel = new ImageDirectoryModel(chosenDir, getImageManager());

        return imageDirectoryModel;
    }

    public ContactSheetListModel getContactSheetModel(String searchString) {

        return new ImageSearchResultsModel(searchString, getImageManager());
    }

    public ContactSheetListModel getContactSheetModel(boolean andMatch, Set<String> selectedKeywords) {

        return new KeywordSearchResultsModel(andMatch, selectedKeywords, getImageManager());

    }

    public int adjustSlideSize(int increment) {

        int slideSize = getConfiguration().getSlideSize() + increment;

        if (slideSize < MIN_SLIDE_SIZE) {
            slideSize = MIN_SLIDE_SIZE;
        }

        if (slideSize > MAX_SLIDE_SIZE) {
            slideSize = MAX_SLIDE_SIZE;
        }

        getConfiguration().setSlideSize(slideSize);

        return slideSize;
    }

    public Map<File, Image> getImageCache() {

        if (imageCache == null) {
            imageCache = new LRUImageCache(getConfiguration().getImageCacheSize());
            // _imageCache = new NullImageCache();
        }

        return imageCache;
    }

    public boolean isImageIO() {

        return getConfiguration().isImageIO();
    }

    public KeywordTreeModel getKeywordTreeModel() {

        if (keywordModel == null) {
            keywordModel = new KeywordTreeModel(getImageBase());

        }
        return keywordModel;

    }

    public MetadataTableModel getMetadataModel() {

        if (metadataModel == null) {
            metadataModel = new MetadataTableModel(null);

        }

        return metadataModel;

    }

    public String getDockingPersistenceFile() {

        return getConfiguration().getDockingPersistenceFile();
    }

}
